package com.wsx.rpc.metrics.timers;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author wangshuaixin
 * @Title: com.wsx.rpc.metrics.timers.TimersTest
 * @Description: 统计某一块代码段的执行时间以及其分布情况，具体是基于Histograms和Meters来实现的
 * @date 2018/11/27
 */
public class TimersTest {

    private static final MetricRegistry REGISTRY = new MetricRegistry();


    private static ConsoleReporter reporter = ConsoleReporter.forRegistry(REGISTRY).build();


    private static final Timer TIMER = REGISTRY.timer(MetricRegistry.name(TimersTest.class, "request"));


    public static void main(String[] args) {
        reporter.start(3, TimeUnit.SECONDS);

        boolean go = true;
        int num = 1;

        Random random = new Random();
        while (go) {
            num ++;
            handlerRequest(random.nextInt(100));

            if (num >= 1000) {
                go = false;
            }
        }
    }


    private static void handlerRequest(int random) {
        Timer.Context context = TIMER.time();
        try {
            Thread.sleep(random);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            context.stop();
        }
    }
}
